import os
import shutil
import yaml
import ast
import impart.data_input
import impart.mariadb_utils
import impart.game
import impart.battle
import impart.entity

#（调用方法，qq号（本人的），qq号（被pk的人的，可无），qq群（本群的，可无），qq群（被pk的群的，可无），pk模式（群pk模式，可无））
#日常事务（qq号）非api调用，如日常增长，每日抽奖，签到
#成就系统（qq号）每次执行完一次。自动检查是否有新成就可获取。
#创建角色（qq群号，qq号）
#自wei（qq号）
#PK（qq号，qq号）/（qq号/pk模式 内外）失败则减少长度并随机注入随机毫升，次数加一
#群体pk（qq群号，qq群号）
#排名（qq号，qq群号）（qq号 世界排名）
#注入查询（qq号）
#成就查询（qq号

# 加载配置文件
def load_config():
    # 获取上一级目录的路径
    parent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
    config_dir = os.path.join(parent_dir, 'config')
    default_config_path = os.path.join(config_dir, 'config_default.yaml')
    user_config_path = os.path.join(config_dir, 'config.yaml')

    # 打印调试信息
    print(f"默认配置文件路径: {default_config_path}")
    print(f"用户配置文件路径: {user_config_path}")

    # 如果用户配置文件不存在，则复制默认配置文件
    if not os.path.exists(user_config_path):
        print(f"在 {user_config_path} 创建用户配置文件")
        try:
            shutil.copyfile(default_config_path, user_config_path)
            print("用户配置文件创建成功。")
        except Exception as e:
            print(f"创建用户配置文件失败: {e}")
            raise
    else:
        print("用户配置文件已存在。")

    # 加载配置文件
    try:
        with open(user_config_path, 'r', encoding='utf-8') as f:
            config = yaml.safe_load(f)
        print("用户配置文件加载成功。")
    except Exception as e:
        print(f"加载用户配置文件失败: {e}")
        raise

    return config

# 使用配置初始化数据库客户端
config = load_config()
db_config = config['database']

# 打印调试信息
print(f"数据库配置: {db_config}")

mc = impart.mariadb_utils.MariadbClient(
    db_config['host'],
    db_config['port'],
    db_config['user'],
    db_config['password'],
    db_config['dbname'],
    poolname=db_config['poolname'],
    pool_size=db_config['pool_size']
)

#自行替换自己的数据库，root是数据库用户名，password是数据库密码
mc.get_conn()

def ban(qq,array):
    if qq in array:
        return True
    else:
        return False

# 把查询语句返回的数组放入player结构体里
#输入qq号，传出plyaer结构体
def select2player(qq_myself):
    player = impart.entity.Player()
    result = mc.query(f"select * from game_player where QQID={qq_myself}")
    #print(result)
    player.QQID = result[0][0]
    player.EffectGroup = result[0][1]
    player.Strong = result[0][2]
    player.Intelligence = result[0][3]
    player.Tili = result[0][4]
    player.Talent = result[0][5]
    player.EXP = result[0][6]
    player.Level = result[0][7]
    player.Way = result[0][8]
    player.Education = result[0][9]
    player.San = result[0][10]
    player.Money = result[0][11]
    player.Charm = result[0][12]
    player.Length = result[0][13]
    player.TodayInjection = result[0][14]
    player.TatallInjection = result[0][15]
    player.TodayFun = result[0][16]
    player.TatalFun = result[0][17]
    player.Tag = ast.literal_eval(result[0][18])
    #print(player.Tag[0])
    player.Weapon = ast.literal_eval(result[0][19])
    #print(player.Weapon[0])
    return player



def deal(fun,qq_myself,qq_pk,qqgroup_myself,qqgroup_pk,pkmode):
    banarray=["2792607647","1447311703","2388272214"]
    if ban(qq_myself,banarray):
        return "请求失败，错误代码：BAN01"
    return_text = ""

    #创建新角色，初始化角色,(fun,qq_myself)
    if(fun=="create"):
        #检测是否存在角色
        if len(mc.query(f"select * from game_player where QQID={qq_myself}"))>0:
            return_text=return_text+"你已拥有牛牛捏，请直接remake吧"
        else:
            #没这个角色,新建角色
            player = impart.game.Init_player(qq_myself,qqgroup_myself)
            mc.insert('game_player',
                      'QQID,EffectGroup,Strong,Intelligence,Tili,Talent,EXP,Level,WAY,Education,San,Money,Charm,Length,TodayInjection,TaltalInjection,TodayFun,TatalFun,Tag,Weapon',
                      f"{player.QQID},{player.EffectGroup},{player.Strong},{player.Intelligence},{player.Tili},{player.Talent},{player.EXP},{player.Level},{player.Way},{player.Education},{player.San},{player.Money},{player.Charm},{player.Length},{player.TodayInjection},{player.TatallInjection},{player.TodayFun},{player.TatalFun},'{player.Tag}','{player.Weapon}'")
            tagname,tagdic = impart.game.get_tag_name(player.Tag[1])
            return_text=return_text+f"【{qq_myself}】开始了自己银乱的一生,你的初始牛牛长度{player.Length}cm,并获得天赋:【{tagname}】,{tagdic}。"

    #remake,输入自己和群号
    if(fun=="remake"):
        #检测是否存在角色
        if len(mc.query(f"select * from game_player where QQID={qq_myself}"))>0:
            #存在角色，开始更改
            player = impart.game.Init_player(qq_myself,qqgroup_myself)
            mc.update('game_player',
                      f"EffectGroup={player.EffectGroup},Strong={player.Strong},Intelligence={player.Intelligence},Tili={player.Tili},Talent={player.Talent},EXP={player.EXP},Level={player.Level},Way={player.Way},Education={player.Education},San={player.San},Money={player.Money},Charm={player.Charm},Length={player.Length},TodayInjection={player.TodayInjection},TaltalInjection={player.TatallInjection},TodayFun={player.TodayFun},TatalFun={player.TatalFun},Tag='{player.Tag}',Weapon='{player.Weapon}'",
                      f"QQID={qq_myself}")
            tagname, tagdic = impart.game.get_tag_name(player.Tag[1])
            return_text=return_text+f"【{qq_myself}】直接remake，你的remake的牛牛长度{player.Length}cm,并remake天赋:【{tagname}】,{tagdic}。"
        else:
            #不存在角色，新建角色
            player = impart.game.Init_player(qq_myself,qqgroup_myself)
            mc.insert('game_player',
                      'QQID,EffectGroup,Strong,Intelligence,Tili,Talent,EXP,Level,WAY,Education,San,Money,Charm,Length,TodayInjection,TaltalInjection,TodayFun,TatalFun,Tag,Weapon',
                      f"{player.QQID},{player.EffectGroup},{player.Strong},{player.Intelligence},{player.Tili},{player.Talent},{player.EXP},{player.Level},{player.Way},{player.Education},{player.San},{player.Money},{player.Charm},{player.Length},{player.TodayInjection},{player.TatallInjection},{player.TodayFun},{player.TatalFun},'{player.Tag}','{player.Weapon}'")
            tagname, tagdic = impart.game.get_tag_name(player.Tag[1])
            return_text = return_text + f"【{qq_myself}】你还没有牛牛捏，我好心给你生成一个牛牛吧,你的初始牛牛长度{player.Length}cm,并获得天赋:【{tagname}】,{tagdic}。"


    #自慰，传入qq
    if(fun=="ziwei"):
        #查询角色信息，确认是否存在，存在则执行，不存在则返回不存在文本
        if len(mc.query(f"select * from game_player where QQID={qq_myself}")) > 0:
            #存在角色
            player = select2player(qq_myself)
            ziwei_text,player = impart.game.ziwei(player)
            return_text = return_text + ziwei_text
            if(impart.game.isEvent()):#是否触发事件
                eventID,eventdic,tagtext,player = impart.game.Event(player)
                event_text = f"!{eventdic}。{tagtext}"
                return_text = return_text + event_text
            player.Level,player.EXP,upgrade_text = impart.game.check_upgrade(player.EXP,player.Level)
            return_text = return_text + upgrade_text
            #提交新的角色信息
            #print(player.Weapon)
            mc.update('game_player',
                      f"EffectGroup={player.EffectGroup},Strong={player.Strong},Intelligence={player.Intelligence},Tili={player.Tili},Talent={player.Talent},EXP={player.EXP},Level={player.Level},Way={player.Way},Education={player.Education},San={player.San},Money={player.Money},Charm={player.Charm},Length={player.Length},TodayInjection={player.TodayInjection},TaltalInjection={player.TatallInjection},TodayFun={player.TodayFun},TatalFun={player.TatalFun},Tag='{player.Tag}',Weapon='{player.Weapon}'",
                      f"QQID={qq_myself}")

        else:
            # 不存在角色
            return_text = return_text + "你还没有牛牛捏，快去生成牛牛叭。"

    #嗦牛子,需要传入qq_myself和qq_pk
    if(fun=='suo'):
        #查询两个角色都存在
        if len(mc.query(f"select * from game_player where QQID={qq_pk}")) > 0:
            if len(mc.query(f"select * from game_player where QQID={qq_myself}")) > 0:
                #这儿双方角色都确认存在，可以开始执行指令
                playera = select2player(qq_myself)
                playerb = select2player(qq_pk)
                suo_text,playera,playerb = impart.game.suo(playera,playerb)
                return_text = return_text + suo_text
                #执行事件和升级
                if (impart.game.isEvent()):  # 是否触发事件
                    eventID, eventdic, tagtext, playera = impart.game.Event(playera)
                    event_text = f"!{eventdic}。{tagtext}"
                    return_text = return_text + event_text
                playera.Level, playera.EXP, upgrade_text = impart.game.check_upgrade(playera.EXP,playera.Level)
                return_text = return_text + upgrade_text
                #提交信息
                mc.update('game_player',
                          f"EffectGroup={playera.EffectGroup},Strong={playera.Strong},Intelligence={playera.Intelligence},Tili={playera.Tili},Talent={playera.Talent},EXP={playera.EXP},Level={playera.Level},Way={playera.Way},Education={playera.Education},San={playera.San},Money={playera.Money},Charm={playera.Charm},Length={playera.Length},TodayInjection={playera.TodayInjection},TaltalInjection={playera.TatallInjection},TodayFun={playera.TodayFun},TatalFun={playera.TatalFun},Tag='{playera.Tag}',Weapon='{playera.Weapon}'",
                          f"QQID={qq_myself}")
                mc.update('game_player',
                          f"EffectGroup={playerb.EffectGroup},Strong={playerb.Strong},Intelligence={playerb.Intelligence},Tili={playerb.Tili},Talent={playerb.Talent},EXP={playerb.EXP},Level={playerb.Level},Way={playerb.Way},Education={playerb.Education},San={playerb.San},Money={playerb.Money},Charm={playerb.Charm},Length={playerb.Length},TodayInjection={playerb.TodayInjection},TaltalInjection={playerb.TatallInjection},TodayFun={playerb.TodayFun},TatalFun={playerb.TatalFun},Tag='{playerb.Tag}',Weapon='{playerb.Weapon}'",
                          f"QQID={qq_pk}")

            else:
                return_text = return_text + "你还没有牛牛捏，快去生成牛牛叭。"
        else:
            return_text = return_text + "对方还没有牛牛捏，你就不要强人所难咯。"

    #pk,需要传入qq_myself和qq_pk
    if(fun=='pk'):
        if len(mc.query(f"select * from game_player where QQID={qq_pk}")) > 0:
            if len(mc.query(f"select * from game_player where QQID={qq_myself}")) > 0:
                # 这儿双方角色都确认存在，可以开始执行指令
                playera = select2player(qq_myself)
                playerb = select2player(qq_pk)
                pk_text, playera, playerb = impart.battle.player_battle(playera, playerb)
                return_text = return_text + pk_text
                #执行事件和升级
                if (impart.game.isEvent()):  # 是否触发事件
                    eventID, eventdic, tagtext, player = impart.game.Event(playera)
                    event_text = f"!{eventdic}。{tagtext}"
                    return_text = return_text + event_text
                playera.Level, playera.EXP, upgrade_text = impart.game.check_upgrade(playera.EXP,playera.Level)
                return_text = return_text + upgrade_text
                # 提交信息
                mc.update('game_player',
                          f"EffectGroup={playera.EffectGroup},Strong={playera.Strong},Intelligence={playera.Intelligence},Tili={playera.Tili},Talent={playera.Talent},EXP={playera.EXP},Level={playera.Level},Way={playera.Way},Education={playera.Education},San={playera.San},Money={playera.Money},Charm={playera.Charm},Length={playera.Length},TodayInjection={playera.TodayInjection},TaltalInjection={playera.TatallInjection},TodayFun={playera.TodayFun},TatalFun={playera.TatalFun},Tag='{playera.Tag}',Weapon='{playera.Weapon}'",
                          f"QQID={qq_myself}")
                mc.update('game_player',
                          f"EffectGroup={playerb.EffectGroup},Strong={playerb.Strong},Intelligence={playerb.Intelligence},Tili={playerb.Tili},Talent={playerb.Talent},EXP={playerb.EXP},Level={playerb.Level},Way={playerb.Way},Education={playerb.Education},San={playerb.San},Money={playerb.Money},Charm={playerb.Charm},Length={playerb.Length},TodayInjection={playerb.TodayInjection},TaltalInjection={playerb.TatallInjection},TodayFun={playerb.TodayFun},TatalFun={playerb.TatalFun},Tag='{playerb.Tag}',Weapon='{playerb.Weapon}'",
                          f"QQID={qq_pk}")

            else:
                return_text = return_text + "你还没有牛牛捏，快去生成牛牛叭。"
        else:
            return_text = return_text + "对方还没有牛牛捏，你就不要强人所难咯。"

    #查询精神状态,传入qq_myself
    if fun=="query":
        if len(mc.query(f"select * from game_player where QQID={qq_myself}")) > 0:
            player = select2player(qq_myself)
            query_text = f'【{player.QQID}】你现在牛牛{round(player.Length,2)}cm，今日被注入{round(player.TodayInjection,2)}ml,总被注入{round(player.TatallInjection,2)}ml。今日x乱次数{player.TodayFun}次,总次数{player.TatalFun}次,力量：{round(player.Strong,2)},智力:{round(player.Intelligence,2)},体力：{round(player.Tili,2)},天赋：{round(player.Talent,2)},经验:{round(player.EXP,2)},等级：{player.Level}，处世之道：{round(player.Way,2)},教育：{round(player.Education,2)}，SAN值：{round(player.San,2)},财富:{round(player.Money,2)},魅力:{round(player.Charm,2)}'
            return_text = return_text + query_text

    #排行榜 传入qqgroup_myself
    if fun == "player_group_rank":
        result = mc.query(f"select QQID,TodayFun from game_player where EffectGroup='{qqgroup_myself}' order by TodayFun DESC limit 0, 10")
        # result是一个[0-9][0-1]的二维数组
        listnum = len(result)
        groupquery_text = f'今日Y趴榜\n堕落之人        寻欢次数\n'
    
        for i in range(listnum):
            groupquery_text += f"{result[i][0]}   {result[i][1]} \n"
        return_text = return_text + groupquery_text
        
    return return_text
